package cn.kgc.springmvc.interceptors;

import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author 课工场
 * @date 2024/2/29
 * @description  登录拦截器
 *
 */
public class LoginInterceptor implements HandlerInterceptor {


    //  目标方法执行之前去执行  /user/add   ->   preHandle   ->  true  放行   false  拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        System.out.println("------------preHandle--------------");
        // 判定用户的身份是否合法  是否登录
        HttpSession session = request.getSession();
        String username = (String) session.getAttribute("username");
        if (username==null){
            session.setAttribute("info","请登录后访问");
            response.sendRedirect("/login.jsp");
            return  false;
        }
        return true ;
    }
}
